//
//  GSUtils.m
//  AgileNYC
//
//  Created by German on 26.05.14.
//  Copyright (c) 2014 Softlegion. All rights reserved.
//

#import "SGSUtils.h"


void GSLog(GSLogType logType, NSString * format, ...) {

#if LOGS_ENABLED

    va_list argumentsList;
    va_start(argumentsList, format);
    
    NSString * strTypeOfLog;
    
    switch (logType) {
            case GSLogInfo:
                    strTypeOfLog = @"INFO:";
#if !LOG_INFOS
                    return;
#endif
                    break;
            case GSLogWarning:
                    strTypeOfLog = @"WARNING:";
#if !LOG_WARNINGS
                    return;
#endif
                    break;
            case GSLogError:
                    strTypeOfLog = @"ERROR:";
#if !LOG_ERRORS
                    return;
#endif
                    break;
            case GSLogEvent:
                    strTypeOfLog = @"EVENT:";
#if !LOG_EVENTS
                    return;
#endif
                    break;
            case GSLogSystem:
                    strTypeOfLog = @"SYSTEM:";
#if !LOG_SYSTEMS
                    return;
#endif
                    break;
            default:
                    strTypeOfLog = @"UNKNOWN:";
    }
    

    NSLogv([NSString stringWithFormat:@"%@ %@",strTypeOfLog,format], argumentsList);
    
    va_end(argumentsList);
#endif

}

NSDate * getDateFromJSON(NSString* dateString) {
    // Expect date in this format "/Date(1268123281843)/"
    
    int startPos = (int)[dateString rangeOfString:@"("].location+1;
    int endPos = (int) [dateString rangeOfString:@")"].location;
    
    NSRange range = NSMakeRange(startPos,endPos-startPos);
    
    unsigned long long milliseconds = [[dateString substringWithRange:range] longLongValue];
    
    GSLog(GSLogInfo, @"%llu",milliseconds);
    NSTimeInterval interval = milliseconds/1000;
    
    return [NSDate dateWithTimeIntervalSince1970:interval];
}

// -1 - not started, 0 - in process, 1 - completed
int checkDateInRange(NSDate * startDate, NSDate * checkDate, NSDate * endDate) {
    NSCalendar * calendar = [NSCalendar currentCalendar];
    
    NSUInteger day1 = [calendar ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:checkDate];
    NSUInteger day2 = [calendar ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:startDate];
    
    if (day2>day1) {
        return -1;
    } else if (day1>day2) {
        return 1;
    } else {
        unsigned int flags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
        
        NSDateComponents * componentsCheckDate = [calendar components:flags fromDate:checkDate];
        NSDateComponents * componentsStartDate = [calendar components:flags fromDate:startDate];
        NSDateComponents * componentsEndDate = [calendar components:flags fromDate:endDate];
        
        NSDate * checkTime = [calendar dateFromComponents:componentsCheckDate];
        NSDate * startTime = [calendar dateFromComponents:componentsStartDate];
        NSDate * endTime = [calendar dateFromComponents:componentsEndDate];
        
        NSComparisonResult compResStart = [checkTime compare:startTime];
        NSComparisonResult compResEnd = [checkTime compare:endTime];
        
        if ((compResStart==NSOrderedDescending) & (compResEnd==NSOrderedAscending)) {
            return 0;
        } else if ((compResStart==NSOrderedSame) || (compResStart==NSOrderedSame)) {
            return 0;
        } else if (compResStart==NSOrderedAscending) {
            return -1;
        } else if (compResEnd==NSOrderedDescending) {
            return 1;
        }
        
        return -2;
    }
}

CGSize labelSize(UILabel * label, CGFloat maxWidth, CGFloat maxHeight) {
    //CGFloat maxWidth = label.frame.size.width;
    //CGFloat maxHeight = 100;
	
    NSMutableParagraphStyle * paragraph = [[NSMutableParagraphStyle alloc] init];
    
    [paragraph setLineBreakMode:label.lineBreakMode];
    [paragraph setAlignment:label.textAlignment];
    
    NSDictionary * attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                 label.font, NSFontAttributeName,
                                 paragraph, NSParagraphStyleAttributeName, nil];
    
    
    CGRect rect = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, CGFLOAT_MAX)
                                                        options:NSStringDrawingUsesLineFragmentOrigin
                                                     attributes:attributes context:nil];
    
    CGSize s = rect.size;
    
    if (s.width < maxWidth)
		s.width = maxWidth;
        
    if (s.height > maxHeight)
        s.height = maxHeight;
        
    return s;
}

NSString * getFormattedPhoneNumber(NSString * phoneNumber) {
    int localNumberMaxLength = 7;
    int areaCodeMaxLength = 3;
    int countryCodeMaxLength = 3;
    
    NSCharacterSet * validatingSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    
    NSArray * validComponents = [phoneNumber componentsSeparatedByCharactersInSet:validatingSet];
    
    NSString * newPhoneNumber = [validComponents componentsJoinedByString:@""];

    if ([newPhoneNumber length] > localNumberMaxLength + areaCodeMaxLength + countryCodeMaxLength) {
        return nil;
    }
    
    NSMutableString * resultString = [NSMutableString string];
    
    NSInteger localNumberLength = MIN([newPhoneNumber length], localNumberMaxLength);
    
    if (localNumberLength>0) {
        
        NSString * number = [newPhoneNumber substringFromIndex:(int)[newPhoneNumber length] - localNumberLength];
        
        [resultString appendString:number];
        
        if ([resultString length] > 3) {
            [resultString insertString:@"-" atIndex:3];
        }
        
    }
    
    if ([newPhoneNumber length] > localNumberMaxLength) {
        
        NSInteger areaCodeLength = MIN((int)[newPhoneNumber length] - localNumberMaxLength, areaCodeMaxLength);
        
        NSRange areaRange = NSMakeRange((int) [newPhoneNumber length] - localNumberMaxLength - areaCodeLength, areaCodeLength);
        
        NSString * area = [newPhoneNumber substringWithRange:areaRange];
        
        area = [NSString stringWithFormat:@"(%@) ", area];
        
        [resultString insertString:area atIndex:0];
    }
    
    if ([newPhoneNumber length] > localNumberMaxLength + areaCodeMaxLength) {
        
        NSInteger countryCodeLength = MIN((int)[newPhoneNumber length] - localNumberMaxLength - areaCodeMaxLength, countryCodeMaxLength);
        
        NSRange countryRange = NSMakeRange(0, countryCodeLength);
        
        NSString * countryCode = [newPhoneNumber substringWithRange:countryRange];
        
        countryCode = [NSString stringWithFormat:@"+%@ ", countryCode];
        
        [resultString insertString:countryCode atIndex:0];
    }
    
    return resultString;
    
    //return @"";
}

NSString * getCurrentStoryBoardName() {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        //return @"Main_iPad";
        return @"iPad";
    } else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        //return @"Main_iPhone";
        return @"iPhone";
    } else {
        return @"";
    }
}




